package org.example.project.common.util;

import org.example.project.common.error.enums.ErrorCode;
import org.example.project.common.error.exception.ServiceException;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Objects;

/**
 * @author wenxy
 * @date 2020/10/15
 */
public class ThrowableUtils {

    /**
     * 获取异常堆栈
     *
     * @param throwable 异常
     * @return 堆栈文本
     */
    public static String getStackTrace(Throwable throwable) {
        if (Objects.isNull(throwable)) {
            return null;
        }

        final StringWriter writer = new StringWriter();
        throwable.printStackTrace(new PrintWriter(writer));
        return writer.toString();
    }

    /**
     * 获取异常堆栈
     *
     * @param errorCode 错误码
     * @param throwable 异常
     * @return 堆栈文本
     */
    public static String getServiceStackTrace(ErrorCode errorCode, Throwable throwable) {
        return getStackTrace(new ServiceException(errorCode, throwable));
    }

}
